/*
 view.go
 Created by hupfei on 2019-09-11
*/

package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/drive/redis"
	"zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
)

type ViewAPI struct {
}

func (a ViewAPI) Name() string {
	return "view API"
}

func (a ViewAPI) Bind() {
	var viewAPI *gin.RouterGroup
	if config.C.RunMode == "debug" {
		viewAPI = config.C.Router.Group("/v1/app/view", middleware.TrackLog(), middleware.AuthMiddleware())
	} else {
		viewAPI = config.C.Router.Group("/v1/app/view", middleware.TrackLog(), middleware.AuthMiddleware(), middleware.CheckInsider())
	}
	{
		viewAPI.GET("cvnt", amountChanged)
		viewAPI.GET("pledge", pledgeData)
		viewAPI.GET("rank", rank)
		viewAPI.GET("user", user)
		viewAPI.GET("node", nodeInfo)
		viewAPI.GET("updateCvntTotal", updateCvntTotal)
	}
}

/*
 * @ Author: hupfei
 * @ Description: 充提数据
 **/
func amountChanged(c *gin.Context) {
	data, err := service.AmountChanged()
	if err != nil {
		api.SendResponse(c, errors.New("查询充提数据失败"), nil)
		return
	}

	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, data)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 质押数据
 **/
func pledgeData(c *gin.Context) {
	data, err := service.PledgeData()
	if err != nil {
		api.SendResponse(c, errors.New("查询质押数据失败"), nil)
		return
	}

	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, data)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 持币排行榜
 **/
func rank(c *gin.Context) {
	data, err := model.GetCvntRankList()
	if err != nil {
		api.SendResponse(c, errors.New("查询持币排行榜失败"), nil)
		return
	}

	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, data)
	return
}

// 用户数据看板
func user(c *gin.Context) {
	data, err := service.ViewUserData()
	if err != nil {
		api.SendResponse(c, errors.New("查询用户看板数据失败"), nil)
		return
	}

	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, data)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 节点详情
 **/
func nodeInfo(c *gin.Context) {
	data, err := service.NodeInfo()
	if err != nil {
		api.SendResponse(c, errors.New("查询节点详情失败"), nil)
		return
	}

	errno.OK.Info = "查询成功"
	api.SendResponse(c, errno.OK, data)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 修改矿池余额
 **/
type updateCvntTotalParams struct {
	Cvnt float64 `form:"cvnt" binding:"required"`
}

func updateCvntTotal(c *gin.Context) {
	var params updateCvntTotalParams
	err := c.ShouldBindQuery(&params)
	if err != nil || params.Cvnt < 0 {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	key := e.BoardPrefix + "view:cvnt"
	_, err = redis.Set(key, params.Cvnt, -1)
	if err != nil {
		errno.OK.Info = "修改失败"
	} else {
		errno.OK.Info = "修改成功"
	}
	api.SendResponse(c, errno.OK, nil)
	return
}
